package com.chenzehe.zdmya.service;

import java.util.List;
import static com.chenzehe.java.core.Status.STATUS_NORMAL;
import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chenzehe.java.core.orm.Page;
import com.chenzehe.java.core.orm.PageRequest;
import com.chenzehe.zdmya.dao.FxDao;
import com.chenzehe.zdmya.domain.Fx;

@Service
@Transactional
public class FxService extends BaseService implements IFxService {
	String hql = "FROM Fx x WHERE status=?";

	@Resource
	FxDao fxDao;

	@Override
	public List<Fx> queryLimitFx(int limit) {
		String hql = "FROM Fx WHERE status=? ORDER BY id DESC";
		return fxDao.findLimit(hql, limit, STATUS_NORMAL.getState());
	}

	@Override
	public Page<Fx> queryFx(PageRequest pageRequest) {
		return fxDao.findPage(pageRequest, hql, STATUS_NORMAL.getState());
	}

	@Override
	public Page<Fx> queryFxByMall(PageRequest pageRequest, String mallEname) {
		String whereHql = " AND mallEname=?";
		return fxDao.findPage(pageRequest, hql + whereHql,
				STATUS_NORMAL.getState(), mallEname);
	}

	@Override
	public Page<Fx> queryFxByCate(PageRequest pageRequest,
			String categoryParentEname) {
		String whereHql = " AND categoryParentEname=?";
		return fxDao.findPage(pageRequest, hql + whereHql,
				STATUS_NORMAL.getState(), categoryParentEname);
	}

	@Override
	public Page<Fx> queryFxByMalllAndCate(PageRequest pageRequest,
			String categoryParentEname, String mallEname) {
		String whereHql = " AND categoryParentEname=? AND mallEname=?";
		return fxDao.findPage(pageRequest, hql + whereHql,
				STATUS_NORMAL.getState(), categoryParentEname, mallEname);
	}

	@Override
	public Fx getById(int id) {
		return fxDao.get(id);
	}

	@Override
	public int updatePingFen(int contentId) {
		String hql = "UPDATE Fx SET zhiCount=zhiCount+1 WHERE id=?";
		return fxDao.batchExecute(hql, contentId);
	}

	@Override
	public String getGoUrl(int id) {
		String hql = "SELECT new Fx(goUrl) FROM Fx WHERE id=?";
		List<Fx> listFx = fxDao.find(hql, id);
		if (listFx != null && listFx.size() > 0) {
			return listFx.get(0).getGoUrl();
		}
		return null;
	}

	@Override
	public int updateCollectionCount(int id) {
		String hql = "UPDATE Fx SET collectionCount=collectionCount+1 WHERE id=?";
		return fxDao.batchExecute(hql, id);
	}

	@Override
	public int updateCommentCount(int id) {
		String hql = "UPDATE Fx SET commentCount=commentCount+1 WHERE id=?";
		return fxDao.batchExecute(hql, id);
	}

	@Override
	public Long queryNumByUser(int userId) {
		String sql = "SELECT COUNT(*) FROM tbl_fx WHERE user_id=? AND status=?";
		return jdbcTemplate.queryForLong(sql, userId, STATUS_NORMAL.getState());
	}
}
